require 'enum'
require 'singleton'
require 'merge/service'
require 'uri'
require 'amatch'

include Amatch

module Merge
  
  class MServices < Enum
    
    class FacebookService < Service
      
      def service_ff_id
        'facebook'
      end
      
    end
    
    class BrightkiteService < Service
      
      def service_ff_id
        'brightkite'
      end
      
    end
    
    class BloggerService < Service
      
      def service_ff_id
        'blog'
      end
      
      protected
      
      def service_ok?(s)
        !(/http:\/\/.*\.blogspot\.com\/?.*/.match(s.user_url_on_service).nil?) && s.ff_id == self.service_ff_id && !s.crawl.nil? && s.crawl.status == 200 && !s.crawl.data.nil?
      end
      
      def service_similar_to_user?(s)
        begin
          uri = URI.parse s.username_on_service
        rescue URI::InvalidURIError => e
          return false
        end
        #uri.host.split('.')[0] == s.user.ff_id
        uri.host.split('.')[0].levenshtein_similar(s.user.ff_id) >= 0.9 
      end
      
      
    end
    
    class LastfmService < Service
      
      def service_ff_id
        'lastfm'
      end
      
    end
    
    class  TwitterService < Service
      
      def service_ff_id
        'twitter'
      end
    end
    
    class StumbleuponService < Service
      
      def service_ff_id
        'stumbleupon'
      end
      
    end
    
    class FlickrService < Service
      
      def service_ff_id
        'flickr'
      end
      
    end
    
    class YoutubeService < Service
      
      def service_ff_id
        'youtube'
      end
      
    end
    
    def filter_services(services)
      r_services = []
      collect.sort {|a,b| a.rank <=> b.rank }.each { |s|
        r = s.find_service services
        r_services << r unless r.nil?
      }
      r_services
    end
    
    protected
    
    def initialize
      super()
      @collections[FacebookService.instance.service_ff_id] = FacebookService.instance
      @collections[BrightkiteService.instance.service_ff_id] = BrightkiteService.instance
      @collections[LastfmService.instance.service_ff_id] = LastfmService.instance
      @collections[StumbleuponService.instance.service_ff_id] = StumbleuponService.instance
      @collections[FlickrService.instance.service_ff_id] = FlickrService.instance
      @collections[BloggerService.instance.service_ff_id] = BloggerService.instance
      @collections[TwitterService.instance.service_ff_id] = TwitterService.instance
      @collections[YoutubeService.instance.service_ff_id] = YoutubeService.instance
      
      FacebookService.instance.rank = 0
      BrightkiteService.instance.rank = 1
      LastfmService.instance.rank = 2
      StumbleuponService.instance.rank = 3
      FlickrService.instance.rank = 4
      BloggerService.instance.rank = 5
      TwitterService.instance.rank = 6
      YoutubeService.instance.rank = 7
    end
    
  end
  
end